﻿using BLL.Base;
using BLL.custom;
using CommandService;
using Entity;
using Entity.DbEntity;
using Entity.SysEntity.Common;
using Entity.ViewEntity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tools;

namespace BLL.Basis
{
    /// <summary>
    /// 存货信息方法类
    /// </summary>
    public class ProductInfoBLL : PubMethod
    {

        LoginInfo userLogin;    //当前登录人信息
        Commands cmd;
        ReturnResult rsl;
        CuDbHelper cuHelper;
        TxtLogHelper txt;
        OperateModel oper;
        List<OperateModel> operList;
        SysFrameWork.SystemBLL sysBLL;
        public ProductInfoBLL()
        {
            userLogin = new LoginInfo();
            cmd = new Commands();
            cuHelper = new CuDbHelper();
            txt = new TxtLogHelper();
            sysBLL = new SysFrameWork.SystemBLL();
        }
       /// <summary>
       /// 存货列表(分页)
       /// </summary>
       /// <param name="pageIndex"></param>
       /// <param name="pageSize"></param>
       /// <param name="pageCount"></param>
       /// <param name="condition"></param>
       /// <returns></returns>
        public ReturnResult InventoryList(string pageIndex, string pageSize,string typeCode, ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" isdel=0  and baseCode='"+ userLogin.UserInfo().baseCode +"' ");
                if (!string.IsNullOrWhiteSpace(typeCode))
                {
                    sb.Append("and typeCode like '" + typeCode + "%'");
                }
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("V_Products_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);
               
                rsl.Data = list;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 存货大类数据列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public ReturnResult InventoryClassList(string pageIndex, string pageSize,ref string pageCount, string condition)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("  baseCode='"+ userLogin.UserInfo().baseCode +"'");
                sb.Append(" and isdel=0 and cCode !='0' ");
                sb = CreateSelectCondition(sb, condition);
                var list = cmd.PageList("V_InvenToryClass_info", pageIndex, pageSize, sb.ToString(), "id desc", ref pageCount);

                var tempList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(JsonConvert.SerializeObject(list));
                if (tempList.Count > 0)
                {
                    foreach (var item in tempList)
                    {
                        if (item["status"].ToString().Equals("open"))
                        {
                            item["statusName"] = "启用";
                        }
                        else
                        {
                            item["statusName"] = "停用";
                        }
                    }
                }
                rsl.Data = tempList;

                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 存货数据同步
        /// </summary>
        /// <param name="isAuto">是否是自动任务</param>
        /// <param name="syncClass">是否只同步存货大类</param>
        /// <returns></returns>
        public ReturnResult SyncInventory(bool isAuto=false,bool syncClass=false)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            string baseCode = "",userCode="" ;
            try
            {
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                    userCode = "admin";
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                    userCode = userLogin.UserInfo().userCode;
                }
                rsl = this.SyncInventoryClass(baseCode,userCode);
                if (!syncClass)
                {
                    if (rsl.Result)
                    {
                        rsl = this.SyncInventoryData(baseCode, userCode, isAuto);
                    }
                }
             
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
   /// <summary>
   /// 存货数据同步
   /// </summary>
   /// <param name="baseCode"></param>
   /// <param name="userCode"></param>
   /// <param name="isAuto"></param>
   /// <returns></returns>
        private ReturnResult SyncInventoryData(string baseCode,string userCode,bool isAuto)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            
            try
            {
             
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                sb.Append("select i.code,i.name,idinventoryclass,isnull(specification,'') cInvStd, ");//编码、名称、类编码、规格
                sb.Append("idunit,");//主计量单位、//辅助计量单位
                sb.Append(" shorthand,i.disabled,");//产品类型编码
                sb.Append("convert(varchar(50),Userfreeitem0) bFree1,convert(varchar(50),Userfreeitem1) bFree2,convert(varchar(50),Userfreeitem2) bFree3,convert(varchar(50),Userfreeitem3) bFree4 ");
                sb.Append("from AA_InventoryEntity i ");
                sb.Append("inner join AA_InventoryClass c on i.idinventoryclass=c.id ");
                sb.Append("and(c.code = '3' or c.code like '03%') ");
                //sb.Append(" left join ComputationUnit cu on p.cAssComUnitCode=cu.cComunitCode");
                sb.Append(" where 1=1");//是否启用启动项
                if (!isAuto)
                {
                    string value = string.Format("-{0}", Tools.ConfigReader.Reader["SyncInventoDay"]);
                    string qydate = DateTime.Now.AddDays(double.Parse(value)).ToString("yyyy-MM-dd");
                    sb.Append(" and i.updated>='" + qydate + "'");//修改时间
                }
                var table =cuHelper.getData(sb.ToString(),baseCode);
                sb.Clear();
                sb.Append("select proCode,baseCode from fun_Inventory_Info where ");
                sb.Append("baseCode='" + baseCode + "'");//只获取账套的存货
                var qTable = cmd.GetDataTable(sb.ToString());

                List<OperateModel> list = new List<OperateModel>();
                DbInventory ven;
                OperateModel oper;
                if (table.Rows.Count > 0)
                {
                    #region 构建数据
                    foreach (DataRow r in table.Rows)
                    {
                        oper = new OperateModel();
                        var dr = qTable.Select("proCode='" + r["code"].ToString().Trim() + "'");
                        ven = new DbInventory();
                        ven.isDel = 0;
                        ven.isSync = "Y";
                        ven.proCode = r["code"].ToString().Trim();
                        ven.proName = r["name"].ToString();
                        ven.typeCode = r["idinventoryclass"].ToString();
                        //ven.cu_kezhong = r["kezhong"].ToString();
                        //ven.cu_xianggui = r["xianggui"].ToString();
                        ven.mUnit = r["idunit"].ToString();
                        //ven.cUnit = r["cUintCode"].ToString();
                        ven.spec = r["cInvStd"].ToString();
                        ven.baseCode = baseCode;
                        #region 判断该存货绑定的自由项
                        var bFrees = "";//自由项
                        if (r["bFree1"].ToString().Equals("1"))
                        {
                            bFrees += "cfree1" + ",";
                        }
                        if (r["bFree2"].ToString().Equals("1"))
                        {
                            bFrees += "cfree2" + ",";
                        }
                        if (r["bFree3"].ToString().Equals("1"))
                        {
                            bFrees += "cfree3" + ",";
                        }
                        if (r["bFree4"].ToString().Equals("1"))
                        {
                            bFrees += "cfree4" + ",";
                        }
                        

                        ven.bFrees = bFrees.TrimEnd(',');
                        #endregion
                        //if (string.IsNullOrWhiteSpace(r["disabled"].ToString()) || DateTime.Parse(r["disabled"].ToString()).Year < 2022)
                        if (string.IsNullOrWhiteSpace(r["disabled"].ToString()) || (r["disabled"].ToString()) == "0")
                        {
                            ven.status = "Y";
                        }
                        else
                        {
                            ven.status = "N";
                        }
                        if (dr.Length < 1)
                        {
                            ven.createtime = getNow();
                            ven.createuser = userCode;
                            oper.Types = OperateModel.OperateType.Add;
                        }
                        else
                        {
                            oper.Types = OperateModel.OperateType.Edit;
                            oper.Conditions = "proCode,baseCode";
                        }

                        oper.Data = ven;
                        list.Add(oper);
                    }
                    #endregion
                }
                else
                {
                    rsl.Message = "更新完成(无数据)";
                    rsl.Result = true;
                }
                if (list.Count > 0)
                {
                    if (list.Count < 1000)
                    {
                        rsl = cmd.MoreUpdate(list);
                    }
                    else
                    {
                        var count = Tools.ConfigReader.Reader["SyncSize"];//读取更新信息条数
                        int pcount = 0;
                        var page = list.Count / int.Parse(count);
                        if (list.Count % int.Parse(count) > 0)
                        {
                            pcount = page + 1;
                        }
                        for (int i = 0; i < pcount; i++)
                        {
                            var qList = list.Skip(i * int.Parse(count)).Take(int.Parse(count)).ToList();
                            rsl = cmd.MoreUpdate(qList);
                            txt.AddLogMsg(string.Format("存货数据同步更新方法({0})，更新结果：{1}", i, JsonConvert.SerializeObject(rsl)));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 存货大类同步
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        private ReturnResult SyncInventoryClass(string baseCode, string userCode)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            try
            {
                //string sql = "select * from AA_InventoryClass ";
                string sql = "select * from AA_InventoryClass where code='3' or code like '03%' ";
                var table = cuHelper.getData(sql,baseCode);//获取T+所有数据
                var qTable = cmd.GetDataTable("select * from fun_InvenClass_Info where baseCode='"+ baseCode +"'");//系统现有所有类数据
                List<OperateModel> list = new List<OperateModel>();
                OperateModel oper ;
                if (table.Rows.Count > 0)
                {
                    var dr = table.Select("depth =1");//获取第一级菜单
                    foreach (DataRow r in dr)
                    {
                        oper = new OperateModel();
                        this.createInventoryClassPar(r, ref oper, qTable, baseCode, userCode,"0");
                        list.Add(oper);
                        this.CallBackInventoryClass(table, 2, r["code"].ToString(), ref list, qTable, baseCode, userCode);
                    }
                }
                if (list.Count > 0)
                {
                    rsl = cmd.MoreUpdate(list);
                }
               
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        
        #region 存货大类递归方法
        /// <summary>
        /// 存货大类递归方法
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="gradeNum">类序号</param>
        /// <param name="cCode">编码</param>
        /// <param name="sysTable">系统目标数据表(查询)</param>
        /// <param name="list"></param>
        private void CallBackInventoryClass(DataTable dt, int gradeNum, string cCode, ref List<OperateModel> list, DataTable sysTable, string baseCode, string userCode)
        {
            var newParentCode = "";
            if ((cCode.Length) % 2 != 0)
            {
                newParentCode = cCode.ToString().PadLeft(cCode.Length + 1, '0');
            }
            else {
                newParentCode = cCode;
            }

            var dr = dt.Select("code like '" + newParentCode + "%' and depth=" + gradeNum);
            if (dr.Length > 0)
            {
                OperateModel oper;

                foreach (DataRow r in dr)
                {
                    oper = new OperateModel();
                    createInventoryClassPar(r, ref oper, sysTable, baseCode, userCode,cCode);
                    list.Add(oper);
                    CallBackInventoryClass(dt, gradeNum + 1, r["code"].ToString(), ref list, sysTable, baseCode, userCode);
                }
            }
        }
        #endregion

        #region 存货大类构建参数方法
        /// <summary>
        /// 存货大类构建参数方法
        /// </summary>
        /// <param name="r">查询结果行</param>
        /// <param name="oper">操作模型</param>
        /// <param name="qTable">查询数据源</param>
        /// <param name="baseCode">账套</param>
        /// <param name="isAuto">是否是自动任务</param>
        private void createInventoryClassPar(DataRow r, ref OperateModel oper, DataTable qTable, string baseCode, string userCode, string parentCode)
        {
            var query = qTable.Select("cCode='" + r["code"].ToString() + "' and baseCode='" + baseCode + "'");
            bool isAdd = true;
            if (query.Length > 0)
            {
                isAdd = false;
            }
            DbInventoryClass venClass = new DbInventoryClass();
            venClass.baseCode = baseCode;
            venClass.cCode = r["code"].ToString();
            venClass.cName = r["name"].ToString();
            venClass.Tid = int.Parse(r["id"].ToString());
            //venClass.id = int.Parse(r["id"].ToString());
            venClass.isSync = "Y";
            venClass.status = "open";
            venClass.parentCode = parentCode;
            venClass.isDel = 0;
            if (isAdd)
            {
                #region 只有在添加状态下 下列值才会添加
                venClass.createtime = getNow();
                venClass.createuser = userCode;
                #endregion
                oper.Types = OperateModel.OperateType.Add;
            }
            else
            {
                oper.Types = OperateModel.OperateType.Edit;
                oper.Conditions = "cCode,baseCode";
            }
            oper.Data = venClass;
        }
        #endregion

        #region 存货大类树结构参数
        /// <summary>
        /// 存货大类树结构参数
        /// </summary>
        /// <returns></returns>
        public ReturnResult venClassNavigation()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select * from fun_InvenClass_Info ");
                sb.Append(" where (status='open' and isdel=0 and baseCode='"+ userLogin.UserInfo().baseCode +"'");
                sb.Append(" or cCode='0') ");
                //sb.Append(" and (cCode='3' or parentCode='3' or parentCode like '03%' ) ");
                var table = cmd.GetDataTable(sb.ToString());//获取全部有效菜单信息


                List<Dictionary<string, object>> menuList = new List<Dictionary<string, object>>();
                #region 构建数据
                //var fMenu = table.Select("parentCode is null");//获取所有父级菜单
                var fMenu = table.Select("parentCode = 0");//获取所有父级菜单
                for (int i = 0; i < fMenu.Length; i++)
                {
                    var fdic = new Dictionary<string, object>();
                    fdic["title"] = string.Format("{0}({1})", fMenu[i]["cName"].ToString(), fMenu[i]["cCode"].ToString());
                    //fdic["id"] = fMenu[i]["cCode"].ToString();
                    fdic["id"] = fMenu[i]["Tid"].ToString();
                    fdic["spread"] = "true";

                    #region 子菜单
                    List<Dictionary<string, object>> cList = new List<Dictionary<string, object>>();
                    this.ChildUrl(table, fMenu[i]["cCode"].ToString(),ref  cList);
                    fdic["children"] = cList;
                    #endregion
                    menuList.Add(fdic);
                }
                #endregion
                rsl.Data = menuList;
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 子菜单生成方法(递归)
        /// </summary>
        /// <param name="table"></param>
        /// <param name="cCode"></param>
        /// <param name="menuName"></param>
        /// <param name="icon"></param>
        /// <param name="chlist"></param>
        private void ChildUrl(DataTable table, string cCode,ref List<Dictionary<string, object>> chlist)
        {
            var dr = table.Select("parentCode='" + cCode + "'");
            if (dr.Length > 0)
            {
                for (int x = 0; x < dr.Length; x++)
                {
                    List<Dictionary<string, object>> tempList = new List<Dictionary<string, object>>();
                    var cdic = new Dictionary<string, object>();
                    cdic["title"] = string.Format("{0}({1})", dr[x]["cName"].ToString(), dr[x]["cCode"].ToString());
                    //cdic["id"] = dr[x]["cCode"].ToString();
                    cdic["id"] = dr[x]["Tid"].ToString();
                    ChildUrl(table, dr[x]["cCode"].ToString(), ref tempList);
                   // cdic["spread"] = "true";
                    cdic["children"] = tempList;
                    chlist.Add(cdic);
                }
            }
        }
       #endregion

        /// <summary>
        /// 存货大类数据显示(不分页)
        /// </summary>
        /// <returns></returns>
        public ReturnResult InventoryClass()
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" select * from fun_InvenClass_Info ");
                sb.Append("where isdel=0 and status='open' ");
               
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 根据存货编码获取存货信息
        /// </summary>
        /// <param name="proCode">存货编码</param>
        /// <returns></returns>
        public ReturnResult GetInventoryByCode(string proCode)
        {
            rsl = new ReturnResult();
            StringBuilder sb = new StringBuilder();
            try
            {
                sb.Append("select * from fun_Inventory_Info where ");
                sb.Append("proCode='"+ proCode +"'");
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    
      /// <summary>
      /// 根据存货编码获取特殊属性
      /// </summary>
      /// <param name="proCode">存货编码</param>
      /// <returns></returns>
        public ReturnResult GetSpecialAttribute(string proCode)
        {
            rsl = new ReturnResult();
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("select c_tssx,'0' shuliang from fun_Inventory_Info where ");
                sb.Append("isdel=0 and baseCode='"+ userLogin.UserInfo().baseCode +"'");
                if (!string.IsNullOrWhiteSpace(proCode))
                {
                    sb.Append(" and proCode='" + proCode + "'");
                }
                rsl.Data = cmd.TableToDictionary(cmd.GetDataTable(sb.ToString()));
                rsl.Result = true;
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取存货自由项配置数据
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncProductCommonData(bool isAuto = false)
        {
            rsl = new ReturnResult();
            
            operList = new List<OperateModel>();
            try
            {
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                #region 获取预设系统参数
                sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where parCode='pCmData'");
                sb.Append(" and isdel=0 and enable='open'");
                var parTable = cmd.GetDataTable(sb.ToString());
                if (parTable.Rows.Count < 1 || string.IsNullOrWhiteSpace(parTable.Rows[0]["parValue"].ToString()))
                {
                    rsl.Message = "预设客户关键参数丢失";
                    return rsl;
                }
                #endregion
                var jsonList = JsonConvert.DeserializeObject<List<JObject>>(parTable.Rows[0]["parValue"].ToString());
                string outPars = "", mPars = "";
                foreach (var obj in jsonList)
                {
                    outPars += "'"+obj["outSysCode"].ToString() + "',";
                    mPars += "'" + obj["mySysCode"].ToString() + "',";
                }
                sb.Clear();
                sb.Append("select cInvCode proCode,cUDValue proValue,bFreeStop,cInvFreeGUID dataId,");
                sb.Append(" cUDID from AA_InvFreeContrapose where cudid in(" + outPars.TrimEnd(',') + ")");
                var table = cuHelper.getData(sb.ToString(),baseCode);//U8自由项数据库
                sb.Clear();
                sb.Append("select * from fun_CommonData_Info where cType in(" + mPars.TrimEnd(',') + ")");
                sb.Append(" and specFile='"+ baseCode +"'");//系统本身通用数据
                var cmTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in table.Rows)
                {
                    var dr = cmTable.Select("cValues='" + r["dataId"].ToString() + "' and parentCode='" + r["proCode"].ToString() + "'");
                    oper = new OperateModel();
                    #region 构建数据
                    DbCommonData cData = new DbCommonData();
                    cData.cCode = r["proValue"].ToString().Trim();
                    cData.cName = r["proValue"].ToString().Trim();
                    cData.parentCode = r["proCode"].ToString().Trim();
                    cData.specFile = baseCode;
                    cData.isDel = 0;
                    if (r["bFreeStop"].ToString().Equals("False") || r["bFreeStop"].ToString().Equals("0"))
                    {
                        cData.status = "Y";
                    }
                    else
                    {
                        cData.status = "N";
                    }
                    foreach (var obj in jsonList)
                    {
                        if (r["cUDID"].ToString() == obj["outSysCode"].ToString())
                        {
                            cData.cType = obj["mySysCode"].ToString();
                            cData.cMemo = obj["sysName"].ToString();
                            break;
                        }
                    }
                    #endregion
                    if (dr.Length > 0)
                    {
                        #region 数据id存在
                        cData.id = int.Parse(dr[0]["id"].ToString());
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        #endregion
                    }
                    else
                    {
                        #region 添加操作
                        cData.createtime = getNow();
                        if (!isAuto)
                        {
                          cData.createuser = userLogin.UserInfo().userCode;
                        }
                        else
                        {
                            cData.createuser = "admin";
                        }
                        cData.cValues = r["dataId"].ToString();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = cData;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    if (operList.Count < 1000)
                    {
                        rsl = cmd.MoreUpdate(operList);
                    }
                    else
                    {
                        var count = Tools.ConfigReader.Reader["SyncSize"];//读取更新信息条数
                        int pcount = 0;
                        var page = operList.Count / int.Parse(count);
                        if (operList.Count % int.Parse(count) > 0)
                        {
                            pcount = page + 1;
                        }
                        for (int i = 0; i < pcount; i++)
                        {
                            var qList = operList.Skip(i * int.Parse(count)).Take(int.Parse(count)).ToList();
                            rsl = cmd.MoreUpdate(qList);
                            txt.AddLogMsg(string.Format("自由项数据更新方法({0})，更新结果：{1}", i, JsonConvert.SerializeObject(rsl)));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 获取存货自由项档案数据
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncProductDefCommonData(bool isAuto = false)
        {
            rsl = new ReturnResult();
            operList = new List<OperateModel>();
            try
            {
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
                #region 获取预设系统参数
                sb.Append("select isnull(parValue,'') parValue from sys_parameters_info where parCode='proDefine'");
                sb.Append(" and isdel=0 and enable='open'");
                var parTable = cmd.GetDataTable(sb.ToString());
                if (parTable.Rows.Count < 1 || string.IsNullOrWhiteSpace(parTable.Rows[0]["parValue"].ToString()))
                {
                    rsl.Message = "预设客户关键参数丢失";
                    return rsl;
                }
                #endregion
                var jsonList = JsonConvert.DeserializeObject<List<JObject>>(parTable.Rows[0]["parValue"].ToString());
                string outPars = "", mPars = "";
                foreach (var obj in jsonList)
                {
                    outPars += "'" + obj["outSysCode"].ToString() + "',";
                    mPars += "'" + obj["mySysCode"].ToString() + "',";
                }
                sb.Clear();
                sb.Append(" select cID dataId,cValue proValue,convert(varchar,bFreeStop) bFreeStop from UserDefine ");
                sb.Append(" where cID in(" + outPars.TrimEnd(',') + ")");
                var table = cuHelper.getData(sb.ToString(), baseCode);//U8自由项数据库
                sb.Clear();
                sb.Append("select * from fun_CommonData_Info where cType in(" + mPars.TrimEnd(',') + ")");
                sb.Append(" and specFile='" + baseCode + "'");//系统本身通用数据
                var cmTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in table.Rows)
                {
                    if (string.IsNullOrWhiteSpace(r["proValue"].ToString()) || r["proValue"].ToString().Trim().Equals("-"))
                    {
                        continue;
                    }
                    var dr = cmTable.Select("cValues='" + r["dataId"].ToString() + "' and cCode='" + r["proValue"].ToString() + "'");
                    oper = new OperateModel();
                    #region 构建数据
                    DbCommonData cData = new DbCommonData();
                    cData.cCode = r["proValue"].ToString().Trim();
                    cData.cName = r["proValue"].ToString().Trim();
                    cData.specFile = baseCode;
                    cData.isDel = 0;
                    if (r["bFreeStop"].ToString() != "0")
                    {
                        cData.status = "N";
                    }
                    else
                    {
                        cData.status = "Y";
                    }
                    foreach (var obj in jsonList)
                    {
                        if (r["dataId"].ToString() == obj["outSysCode"].ToString())
                        {
                            cData.cType = obj["mySysCode"].ToString();
                            cData.cMemo = obj["sysName"].ToString();
                            break;
                        }
                    }
                    #endregion
                    if (dr.Length > 0)
                    {
                        #region 数据id存在
                        cData.id = int.Parse(dr[0]["id"].ToString());
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        #endregion
                    }
                    else
                    {
                        #region 添加操作
                        cData.createtime = getNow();
                        if (!isAuto)
                        {
                            cData.createuser = userLogin.UserInfo().userCode;
                        }
                        else
                        {
                            cData.createuser = "admin";
                        }
                        cData.cValues = r["dataId"].ToString();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = cData;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    if (operList.Count < 1000)
                    {
                        rsl = cmd.MoreUpdate(operList);
                    }
                    else
                    {
                        var count = Tools.ConfigReader.Reader["SyncSize"];//读取更新信息条数
                        int pcount = 0;
                        var page = operList.Count / int.Parse(count);
                        if (operList.Count % int.Parse(count) > 0)
                        {
                            pcount = page + 1;
                        }
                        for (int i = 0; i < pcount; i++)
                        {
                            var qList = operList.Skip(i * int.Parse(count)).Take(int.Parse(count)).ToList();
                            rsl = cmd.MoreUpdate(qList);
                            txt.AddLogMsg(string.Format("自由项档案数据更新方法({0})，更新结果：{1}", i, JsonConvert.SerializeObject(rsl)));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
        /// <summary>
        /// 存货计量单位同步
        /// </summary>
        /// <param name="isAuto"></param>
        /// <returns></returns>
        public ReturnResult SyncProductUnit(bool isAuto = false)
        {
            rsl = new ReturnResult();
            SysFrameWork.SystemBLL sysBLL = new SysFrameWork.SystemBLL();
            operList = new List<OperateModel>();
            try
            {
                string baseCode = "";
                #region 账套选择
                if (isAuto)
                {
                    baseCode = sysBLL.getDefaultBaseCode();
                }
                else
                {
                    baseCode = userLogin.UserInfo().baseCode;
                }
                #endregion
                if (string.IsNullOrWhiteSpace(baseCode))
                {
                    rsl.Message = "数据库编码获取失败";
                    return rsl;
                }
                StringBuilder sb = new StringBuilder();
            
               
                sb.Clear();
                sb.Append("select cComunitCode,cComUnitName,cGroupCode,pubufts dataId from ComputationUnit");
                var table = cuHelper.getData(sb.ToString(), baseCode);//U8全部计量单位数据
                sb.Clear();
                sb.Append("select * from fun_CommonData_Info where cType='cUnit'");
                sb.Append(" and specFile='" + baseCode + "'");//系统全部计量单位数据
                var cmTable = cmd.GetDataTable(sb.ToString());
                foreach (DataRow r in table.Rows)
                {
                    var dr = cmTable.Select("cCode='" + r["cComunitCode"].ToString() + "'");
                    oper = new OperateModel();
                    #region 构建数据
                    DbCommonData cData = new DbCommonData();
                    cData.cCode = r["cComunitCode"].ToString().Trim();
                    cData.cName = r["cComUnitName"].ToString().Trim();
                    cData.parentCode = r["cGroupCode"].ToString().Trim();
                    cData.cType = "cUnit";
                    cData.cMemo = "计量单位";
                    cData.isSys = "0";
                    cData.specFile = baseCode;
                    cData.isDel = 0;
                    cData.status = "Y";
                  
                    #endregion
                    if (dr.Length > 0)
                    {
                        #region 修改
                        cData.id = int.Parse(dr[0]["id"].ToString());
                        oper.Types = OperateModel.OperateType.Edit;
                        oper.Conditions = "id";
                        #endregion
                    }
                    else
                    {
                        #region 添加操作
                        cData.createtime = getNow();
                        if (!isAuto)
                        {
                            cData.createuser = userLogin.UserInfo().userCode;
                        }
                        else
                        {
                            cData.createuser = "admin";
                        }
                        cData.cValues = r["dataId"].ToString();
                        oper.Types = OperateModel.OperateType.Add;
                        #endregion
                    }
                    oper.Data = cData;
                    operList.Add(oper);
                }
                if (operList.Count > 0)
                {
                    if (operList.Count < 1000)
                    {
                        rsl = cmd.MoreUpdate(operList);
                    }
                    else
                    {
                        var count = Tools.ConfigReader.Reader["SyncSize"];//读取更新信息条数
                        int pcount = 0;
                        var page = operList.Count / int.Parse(count);
                        if (operList.Count % int.Parse(count) > 0)
                        {
                            pcount = page + 1;
                        }
                        for (int i = 0; i < pcount; i++)
                        {
                            var qList = operList.Skip(i * int.Parse(count)).Take(int.Parse(count)).ToList();
                            rsl = cmd.MoreUpdate(qList);
                            txt.AddLogMsg(string.Format("自由项数据更新方法({0})，更新结果：{1}", i, JsonConvert.SerializeObject(rsl)));
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                rsl.Message = ex.Message;
            }
            return rsl;
        }
    }
}
